package org.oims.simpleserver.emiter;

import org.oims.simpleserver.entities.event.EndpointClosed;
import org.oims.simpleserver.entities.event.EndpointToken;
import org.oims.simpleserver.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.util.HashMap;
import java.util.Map;

@Controller
public class EventEmitter {
    private Map<String, EventHandler> handlerMap = new HashMap<>();
    private UserService userService;

    public EventEmitter(){
        init();
    }
    /**
     *
     */
    private void init(){
        this.on("endpoint-token", data -> {
            EndpointToken endpointToken = (EndpointToken) data;
            userService.registerEndpoint(endpointToken.getToken(), endpointToken.getEndpoint());
        });
        this.on("endpoint-closed", data -> {
            EndpointClosed endpointClosed = (EndpointClosed) data;
            userService.closeEndpoint(endpointClosed.getId(), endpointClosed.getEndpoint());
        });
    }

    /**
     *
     * @param eventName
     * @param handler
     */
    public void on(String eventName, EventHandler handler){
        this.handlerMap.put(eventName, handler);
    }

    /**
     *
     * @param eventName
     * @param data
     */
    public void emit(String eventName, Object data){
        EventHandler handler = this.handlerMap.get(eventName);
        if(handler != null){
            try{
                handler.handle(data);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }
}
